﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using AUV5.Common;

namespace JQueryUploadify
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {
        int minheight = CommonDefine.SERVICE_THUMB_HEIGHT;
        int minwidth = CommonDefine.SERVICE_THUMB_WIDTH;
        
        public void ProcessRequest(HttpContext context)
        {
            Stream str = null;
            System.Drawing.Image img = null; 
            try
            {
                context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";
                HttpPostedFile file = context.Request.Files["Filedata"];
                string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);
                string serverPath = context.Request["folder"] + FileHelper.GetUniqueFileName() + Path.GetExtension(file.FileName); 
                if (file != null)
                {
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    //如果是图片文件,判断大小后上传
                    string ext = Path.GetExtension(file.FileName).ToLower();
                    if (ext == ".jpg" || ext == ".png")
                    {
                        str = file.InputStream;
                        img = System.Drawing.Image.FromStream(str);

                        if (img.Width >= minwidth && img.Height >= minheight)
                        {
                            file.SaveAs(HttpContext.Current.Server.MapPath(serverPath));
                            context.Response.Write(serverPath);
                        }
                        else
                        {
                            context.Response.Write("图片尺寸必须大于" + minwidth + "*" + minheight);
                        }
                    }
                    //如果是视频，则直接上传
                    else
                    {
                        file.SaveAs(HttpContext.Current.Server.MapPath(serverPath));
                        context.Response.Write(serverPath);
                    }
                }
                else
                {
                    context.Response.Write("上传文件为空");
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (str != null)
                {
                    str.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
            }
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}